from django.shortcuts import render

# Create your views here.

from django.views import View
from apps.areas.models import Area
from django.http import JsonResponse
from django.core.cache import cache
class ProvienceView(View):
    def get(self,request):
        data_list = cache.get('province')
        if data_list is None:
            areas = Area.objects.filter(parent__isnull=True)

            data_list = []
            for area in areas:
                data_list.append({
                    'id':area.id,
                    'name':area.name
                })

            cache.set('province',data_list,24*3600)
        return JsonResponse({
            "code": "0",
            "errmsg": "OK",
            'province_list':data_list})



class SubAreaView(View):
    def get(self,request,parent_id):
        # 1.获取 省[市] 的id
        # 2. 根据 省[市] 的id 获取下一级数据
        subs_list = cache.get('city_%s'%parent_id)
        if subs_list is None:

            # 方式1
            # areas = Area.objects.filter(parent_id=parent_id)
            # cache.get()
            # 方式2

            pro_city_id = Area.objects.get(id =parent_id)
            # areas = pro_city_id.areas_set.all()
            areas = pro_city_id.subs.all()
            subs_list = []

            for area in areas:
                subs_list.append({
                    'id':area.id,
                    'name':area.name
                })

            cache.set('city_%s'%parent_id,subs_list,24*3600)

        # 4.返回响应
        return JsonResponse({
            "code": "0",
            "errmsg": "OK",
            "sub_data": {
                "subs": subs_list
            }
        })